<?php
/**
 * Created by PhpStorm.
 * User: baidu
 * Date: 17/8/5
 * Time: 下午4:37
 */
namespace app\api\controller\v1;

use app\api\controller\Common;
use think\Controller;
use app\common\lib\exception\ApiException;
// use app\common\lib\Aes;

class News extends Common {

   public function index(){
      // 1.自动验证机制

      $data = input('get.');
      $whereData['status'] = config('code.status_normal');

      if(!empty($data['catid'])) {
          $whereData['catid'] = input('get.catid', '1', 'intval');
      }
      if (!empty($data['title'])) {
          $whereData['title'] = [
            'like','%'.$data['title'].'%'
          ];
      }
      //分页信息
      $this->getPageAndSize($data);
      //获取表里的数据
      try {
          $total=model('News')->getNewsCountCondition($whereData);
      } catch (\Exception $e) {
          return new ApiException('error', 400);
      }

      try {
          $news = model('News')->getNewsByCondition($whereData,$this->form,$this->size);
      } catch (\Exception $e) {
          return new ApiException('error', 400);
      }

      $result = [
        'total'=>$total,
        'page_mum' => ceil($total/$this->size),
        'list' => $this->getDealNews($news),
      ];
      return show(config('code.success'),'ok',$result,200);
   }

   /**
    * 获取详情页
    * 详情接口
    */
   public function read(){
      //详情页app ->> 1:x.com/3.html   2:接口
      $id = input('param.id',0,'intval');
      if (empty($id)) {
        return new ApiException('id no exit', 400);
      }

      //通过id获取表中数据
      try {
        $news = model('News')->get($id);
      } catch (\Exception $e) {
        return new ApiException('sql error', 400);
      }

      if (empty($news) && $news->status == config('code.status_normal')) {
        return new ApiException('no exit news', 400);
      }

     try {
            model('News')->where(['id' => $id])->setInc('read_count');
       }catch(\Exception $e) {
            return new ApiException('error', 400);
       }

      $cats = config('cat.lists');
      $news->catname = $cats[$news->catid];

      return show(config('code.success'),'ok',$news,200);
   }

}